extends Node2D

class_name Monster

@onready var intent = $Intent
@onready var state_bar = $StateBar

var state: MonsterState:
	set = set_monster_state
var monster_action_picker: MonsterActionPicker
var placeholder


func _ready():
	setup_ai()
	setup_animation()
	state.update_intent_signal.connect(intent.update_intent_value.bind(self))


func set_monster_state(value: MonsterState) -> void:
	state = value.create_instance()
	if not state.state_changed.is_connected(update_state):
		state.state_changed.connect(update_state)


func init_state() -> void:
	$HPLabel.set_text(str(state.health))
	$StateBar.init_state(state)


func update_state(type: StateBar.STATE = StateBar.STATE.NOTHING, value = 0, duration = 0) -> void:
	$HPLabel.set_text(str(state.health))
	state_bar.state_match(type, value, duration)


func setup_ai() -> void:
	if monster_action_picker:
		monster_action_picker.queue_free()

	if state.ai == null:
		return
	var new_action_picker: MonsterActionPicker = state.ai.instantiate()
	add_child(new_action_picker)
	monster_action_picker = new_action_picker
	monster_action_picker.monster = self
	var player = get_tree().get_first_node_in_group("player")
	monster_action_picker.target = player

	var action = monster_action_picker.get_action()
	intent.update_intent(action)


func setup_animation() -> void:
	var animate: AnimatedSprite2D = $AnimatedSprite2D
	animate.sprite_frames = state.act_sprite_frames
	animate.play("default")


func before_round():
	print("before_round")
	state_bar.before_round(state)
	pass


func after_round():
	print("after_round")
	var action = monster_action_picker.get_action()
	intent.update_intent(action)
	state_bar.after_round(state)


func in_round():
	print("in_round")
	var action = monster_action_picker.current_action
	if action:
		action.perform_action()


func take_damage(damage):
	state.take_damage(damage)
	if state.health <= 0:
		CardManager.round_data.killed_monster += 1
		CardManager.round_data.died_monster.append(self)


func trial_take_damage(damage, times):
	return state.trial_take_damage(damage, times)
		
		
func _on_mouse_entered():
	Globals.current_monster = self


func _on_mouse_exited():
	Globals.current_monster = null


func play_animation(s):
	var animate: AnimatedSprite2D = $AnimatedSprite2D
	animate.play(s)
